package com.itheima.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @email 1572178030@qq.com
 * @author:黄海宾
 * @date: 2023/2/6  9:46
 * 页面过滤器
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginFilter implements Filter {

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        log.info("拦截器");
        //要存在session中
        HttpServletRequest req = (HttpServletRequest) request;
        //给前端返回数据要的
        HttpServletResponse resp = (HttpServletResponse) response;

        String urlName = req.getRequestURI();

        log.info("拦截到请求：{}", urlName);
        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",
                "/user/sendMsg"
        };

        boolean check = check(urlName, urls);
        log.info("check：{}", check);
        //如果时true就放行
        if (check) {
            log.info("本次请求{}不需要处理", urlName);
            filterChain.doFilter(req, resp);
            return;
        }
        if (req.getSession().getAttribute("employee") != null) {
            log.info("本次请求{}不需要处理", urlName);

            //谁进入就会走过滤器，保存该进入的用户的id
            Long empId = (Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(req, resp);
            return;
        }
        //4-2、判断登录状态，如果已登录，则直接放行
        if(req.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",req.getSession().getAttribute("user"));

            Long userId = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }
        log.info("用户未登录");
        resp.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls
     * @param urlName
     * @return
     */
    public boolean check(String urlName, String[] urls) {
        for (String url : urls) {
            //顺序不要反了
            boolean match = PATH_MATCHER.match(url, urlName);
            System.out.println(match);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
